'use client';

import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { updateUserStatusInfo } from '@/services/api';
import type { IDifference, IUser } from '@/interfaces';
import diff from 'microdiff';
import useToast from '@/hooks/useToast';
import { getDiffData } from '@/lib/tool';
import Box from '@/app/[locale]/admin/common/box';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function UpdateUserAccountState({
  source,
  translatedFields,
}: {
  source: IUser;
  translatedFields: PrefixedTTranslatedFields<'userAdminPage'>;
}) {
  const [form, setForm] = useState<{
    accountNonExpired?: boolean;
    credentialsNonExpired?: boolean;
    accountNonLocked?: boolean;
    enabled?: boolean;
  }>({
    accountNonExpired: source.accountNonExpired,
    credentialsNonExpired: source.credentialsNonExpired,
    accountNonLocked: source.accountNonLocked,
    enabled: source.enabled,
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const { show } = useToast();
  const [isDisabledSave, setIsDisabledSave] = useState(true);

  const updateUserStatusInfoMutation = useMutation(updateUserStatusInfo);

  useEffect(() => {
    const diffData = diff(
      {
        accountNonExpired: source.accountNonExpired,
        credentialsNonExpired: source.credentialsNonExpired,
        accountNonLocked: source.accountNonLocked,
        enabled: source.enabled,
      },
      form,
    );
    setDifferenceData(diffData);
    setIsDisabledSave(diffData.length === 0);
  }, [form, source]);

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const data = getDiffData(differenceData);
      const id = source.id;
      await updateUserStatusInfoMutation.mutateAsync({
        id,
        data,
      });

      show({
        type: 'SUCCESS',
        message: translatedFields.operate.updateCompleted,
      });
    } catch (e) {
      updateUserStatusInfoMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setDifferenceData([]);
    }
  }

  function onChangeForm(e: ChangeEvent<HTMLInputElement>) {
    const name = e.target.name;
    const value = e.target.checked;
    setForm({ ...form, [name]: value });
  }

  return (
    <Box>
      <form onSubmit={onClickSave} className="vstack gap-4">
        <div className="form-control vstack gap-4">
          <div className="form-check form-switch">
            <input
              className="form-check-input"
              type="checkbox"
              role="switch"
              id="yw-admin-user-state-accountNonExpired"
              name="accountNonExpired"
              checked={form.accountNonExpired}
              onChange={onChangeForm}
            />
            <label
              className="form-check-label"
              htmlFor="yw-admin-user-state-accountNonExpired"
            >
              {translatedFields.properties.accountNonExpired}
            </label>
          </div>
          <div className="form-check form-switch">
            <input
              className="form-check-input"
              type="checkbox"
              role="switch"
              id="yw-admin-user-state-accountNonLocked"
              name="accountNonLocked"
              checked={form.accountNonLocked}
              onChange={onChangeForm}
            />
            <label
              className="form-check-label"
              htmlFor="yw-admin-user-state-accountNonLocked"
            >
              {translatedFields.properties.accountNonLocked}
            </label>
          </div>
          <div className="form-check form-switch">
            <input
              className="form-check-input"
              type="checkbox"
              role="switch"
              id="yw-admin-user-state-credentialsNonExpired"
              name="credentialsNonExpired"
              checked={form.credentialsNonExpired}
              onChange={onChangeForm}
            />
            <label
              className="form-check-label"
              htmlFor="yw-admin-user-state-credentialsNonExpired"
            >
              {translatedFields.properties.credentialsNonExpired}
            </label>
          </div>
          <div className="form-check form-switch">
            <input
              className="form-check-input"
              type="checkbox"
              role="switch"
              id="yw-admin-user-state-enabled"
              name="enabled"
              checked={form.enabled}
              onChange={onChangeForm}
            />
            <label
              className="form-check-label"
              htmlFor="yw-admin-user-state-enabled"
            >
              {translatedFields.properties.enabled}
            </label>
          </div>
        </div>

        <button
          type="submit"
          disabled={updateUserStatusInfoMutation.isLoading || isDisabledSave}
          className="btn btn-success col col-lg-2 my-4"
        >
          {updateUserStatusInfoMutation.isLoading && <Spinner classs="me-2" />}
          {translatedFields.operate.update}
        </button>
      </form>
    </Box>
  );
}
